package table

import (
	"fmt"
	"gorm.io/gorm"
	"i18n-template/components"
	"i18n-template/utils"
)

type Users struct {
	gorm.Model
	Username string `json:"username" gorm:"type:string;size:256"`
	Password string `json:"password" gorm:"type:string;size:256"`
	Mobile   string `json:"mobile" gorm:"type:string;size:256"`
}

func (u Users) TableName() string {
	return "users"
}
func (u Users) FindUserByUsername(username string) (*Users, error) {
	user := &Users{}
	err := components.DB.Model(&Users{}).Where("username = ?", username).First(user).Error
	return user, err
}
func (u Users) FindAllUserByUsername(username string) ([]*Users, error) {
	user := make([]*Users, 20)
	fmt.Println("user ", username)
	err := components.DB.Model(&Users{}).Where(fmt.Sprintf("username LIKE '%s'", "%"+username+"%")).Find(&user).Error
	return user, err
}

func (u Users) FindUserByID(id uint) (*Users, error) {
	user := &Users{}
	err := components.DB.Model(&Users{}).Where("id = ?", id).First(user).Error
	return user, err
}

func (u Users) GenerateUser(user *Users) error {
	return components.DB.Model(&Users{}).Save(user).Error
}

func (u Users) PatchUserByID(user *Users) error {
	if user.Password != "" {
		user.Password = utils.HandlerPwdHash256Encrypt(user.Password)
	}
	return components.DB.Model(&Users{}).Where("id = ?", user.ID).
		Updates(Users{Username: user.Username, Password: user.Password, Mobile: user.Mobile}).Error
}

func (u Users) DeleteUserByID(user *Users) error {
	return components.DB.Model(&Users{}).Where("id = ?", user.ID).
		First(&Users{}).Delete(&Users{}).Error
}

func (u Users) FindAllUsers() []Users {
	var users []Users
	components.DB.Model(&Users{}).Find(&users)
	return users
}
